import { NativeModules } from "react-native";

type RNMMKVModule = {
  save(key: string | undefined, value: string | undefined): boolean
  get(key: string | undefined): string | undefined
}

const RNMMKVModule = NativeModules.RNMMKVModule as RNMMKVModule;

class RNMMKV {

  static saveString(key: string | undefined, value: string | undefined): boolean {
    return this.save(key, value);
  }

  static saveBoolean(key: string | undefined, value: boolean): boolean {
    return this.save(key, String(value));
  }

  static getString(key: string | undefined): string | undefined {
    return this.get(key);
  }

  static getBoolean(key: string | undefined): boolean {
    const value = this.get(key);
    if (value) {
      return value == "true";
    }
    return false;
  }


  /**
   * 保存 KV到本地
   * @param key
   * @param value
   * @return 保存结果
   */
  private static save(key: string | undefined, value: string | undefined): boolean {
    if (!key || !value) return false;
    return RNMMKVModule.save(key, value);
  }

  /**
   * 根据 Key 读取值
   * @param key
   * @return 值
   */
  private static get(key: string | undefined): string | undefined {
    return RNMMKVModule.get(key);
  }
}


export default RNMMKV;
